package com.shaodongbo.demo_4;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;

import java.util.ArrayList;

public class StuAdapter extends BaseAdapter {
    private ArrayList<Student> studentArrayList;
    private Context context;
    private IonDelListener listener;

    public StuAdapter(Context context, ArrayList<Student> studentArrayList, IonDelListener listener){
        this.context = context;
        this.listener = listener;
        this.studentArrayList = studentArrayList;
    }

    public void changeData(ArrayList<Student> studentArrayList){
        this.studentArrayList = studentArrayList;
        notifyDataSetChanged();
    }

    @Override
    public int getCount() {
        return studentArrayList.size();
    }

    @Override
    public Object getItem(int position) {
        return studentArrayList.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    int count = 0;
    @Override
    public View getView(final int position, View convertView, ViewGroup parent) {
        if(convertView == null){
            count++;
            LayoutInflater layoutInflater = LayoutInflater.from(context);
            convertView = layoutInflater.inflate(R.layout.list_item, parent, false);

            StuViewHolder holder = new StuViewHolder();
            holder.headImg = convertView.findViewById(R.id.headView);
            holder.nameView = convertView.findViewById(R.id.nameView);
            holder.ageView = convertView.findViewById(R.id.ageView);
            holder.ivDel = convertView.findViewById(R.id.iv_del);

            convertView.setTag(holder);
        }

        Student student = studentArrayList.get(position);
        StuViewHolder holder = (StuViewHolder) convertView.getTag();

        holder.headImg.setImageResource(student.getImgid());
        holder.nameView.setText(student.getName());
        holder.ageView.setText(String.valueOf(student.getAge()));

        holder.ivDel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                listener.del(position);
            }
        });

        return convertView;
    }
}
